package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author 陈辉
 * @data 2023 17:10
 */
@Service
@Slf4j
@Transactional
public class ArticleFreemarkerServiceImpl  implements ArticleFreemarkerService {
    @Autowired
    private Configuration configuration;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private KafkaTemplate<String,String>kafkaTemplate;

    /**
     * 生成静态文件上传到minIO中
     * @param apArticle
     * @param content
     */
    @Async
    @Override
    public void buildArticleToMinIO(ApArticle apArticle, String content) {
        if (StringUtils.isNotEmpty(content)){
            try {
                //1. 基于freemark进行详情页的合成：数据+模板
                //1.1 拿到模板
                Template template = configuration.getTemplate("article.ftl");
                //1.2 数据封装
                Map<String,Object>map = new HashMap<>();
                map.put("content", JSON.parseArray(content));
                //1.3 合成页面
                StringWriter sw = new StringWriter();
                template.process(map,sw);

                //2. 将合成的页面数据上传到minIO
                InputStream is = new ByteArrayInputStream(sw.toString().getBytes());
                String path = fileStorageService.uploadHtmlFile("", UUID.randomUUID().toString() + ".html", is);

                //3. 将MinIO上传成功后返回的详情页url回填到数据库表：static_url属性上
                apArticleMapper.update(apArticle, Wrappers.<ApArticle>lambdaUpdate().eq(ApArticle::getId,apArticle.getId())
                        .set(ApArticle::getStaticUrl,path));

                //4. 发送消息到kafka，通知search微服务同步新的文章到ES中
                SearchArticleVo vo = SearchArticleVo.builder()
                        .id(apArticle.getId())
                        .title(apArticle.getTitle())
                        .publishTime(apArticle.getPublishTime())
                        .layout(Integer.valueOf(apArticle.getLayout()))
                        .images(apArticle.getImages())
                        .authorId(apArticle.getAuthorId())
                        .authorName(apArticle.getAuthorName())
                        .staticUrl(path)
                        .content(content)
                        .build();

                kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC,JSON.toJSONString(vo));
            }catch (Exception e){
                e.printStackTrace();
            }
        }


    }
}
